# 增加删除用户接口
from django.http import HttpResponse, JsonResponse
from rest_framework import status
from rest_framework.utils import json
from rest_framework.views import APIView
from apitest.models import Project
from apitest.serializers import ProjectSerializer
from apitest.views import DocParam

def json_response(res, errcode,errmsg):
    data = {
        "errcode": errcode,
        "errmsg":errmsg,
        "data": res,
    }
    return JsonResponse(data,safe=False)

def json_to_dict(request):
    json_str=request.body
    dict_data = json.loads(json_str)
    return dict_data

class CreateProject(APIView):
    """创建项目接口"""
    coreapi_fields = (
        DocParam("project_name", required=True, description="项目名称", type="string", ),
        DocParam("owner_id", required=True, description="负责人，关联用户表id", type="string", ),
        DocParam("desc", required=True, description="项目描述", type="string", ),
    )

    def post(self, request):
        dict_data=json_to_dict(request)
        projectser = ProjectSerializer(data=dict_data)
        if projectser.is_valid():
            projectser.create(projectser.validated_data)
            # return JsonResponse(data=projectser.data)
            return json_response(projectser.data,ret=1)



class SelectProject(APIView):
    """查询项目接口"""

    def get(self, request):
        result = Project.objects.all()
        serializer = ProjectSerializer(result, many=True)
        return JsonResponse(serializer.data, safe=False)


class UpdateProject(APIView):
    """修改项目接口"""
    coreapi_fields = (
        DocParam("project_name", description="项目名称", type="string", ),
        DocParam("owner_id", description="负责人，关联用户表id", type="string", ),
        DocParam("desc", description="项目描述", type="string", ),
    )

    def post(self, request):
        json_str=request.body
        dict_data = json.loads(json_str)
        Project.objects.filter(owner_id=dict_data.get("owner_id")).update(
            project_name=dict_data.get("project_name"), owner_id=dict_data.get("owner_id"),
            desc=dict_data.get("desc"))
        return JsonResponse(dict_data, safe=False)

    # def post(self, request): #获取表单数据
    #     Project.objects.filter(owner_id=request.GET.get("owner_id")).update(
    #             project_name=request.GET.get("project_name"), owner_id=request.GET.get("owner_id"),
    #             desc=request.GET.get("desc"))
    #     return JsonResponse(request.GET)


class DeleteProject(APIView):
    """删除已创建项目"""
    coreapi_fields = (
        DocParam("project_name", description="项目名称", type="string", ),
    )

    def post(self, request):
        json_str = request.body
        dict_data = json.loads(json_str)
        Project.objects.filter(project_name=dict_data.get("project_name")).delete()
        return JsonResponse(dict_data, safe=False)
